<template>
  <div class="settings-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 面包屑,路径导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row>
        <el-col :span="15">
          <!-- 表单 -->
          <el-form ref="form" :model="user" label-width="80px" class="userForm">
            <el-form-item label="编号">{{user.id}}</el-form-item>
            <el-form-item label="手机">{{user.mobile}}</el-form-item>
            <el-form-item label="媒体名称">
              <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="媒体介绍">
              <el-input type="textarea" v-model="user.intro"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="user.email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onUpdateUser">保存</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="5" :offset="2">
          <!-- <p @click="$refs.file.click()">修改头像</p> -->
          <label for="file">
            <el-avatar shape="square" :size="120" fit="cover" :src="user.photo"></el-avatar>
            <p>点击修改头像</p>
          </label>
          <input type="file" hidden ref="file" id="file" @change="inputChange" />
        </el-col>
      </el-row>
    </el-card>
    <!-- 图片裁剪弹出框 -->
    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      append-to-body
      @opened="onDialogOpend"
      @closed="onDialogClosed"
    >
      <div class="preview-img-wrap">
        <img :src="previewImg" ref="preview-img" class="preview-img" alt />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onUpdateImg" :loading="updateProfileLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, updateUserPhoto, updateUserProfile } from "@/api/user";
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import Bus from "@/utils/global-bus";

export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      user: {
        email: "",
        id: null,
        intro: "",
        mobile: "",
        name: "",
        photo: ""
      },
      dialogVisible: false, // 控制头像上传对话框
      previewImg: "", // 上传图片预览
      updateProfileLoading: false, // 更新基本信息按钮loading
      cropper: null // 裁切器实例
    };
  },
  computed: {},
  watch: {},
  created() {
    this.loadUser();
  },
  mounted() {},
  methods: {
    loadUser() {
      getUserProfile().then(res => {
        console.log(res);
        this.user = res.data.data;
      });
    },
    inputChange() {
      // 处理图片预览
      const file = this.$refs.file;
      const blobData = window.URL.createObjectURL(file.files[0]);
      // console.log(blobData)
      this.previewImg = blobData;
      // 展示弹窗，预览选择图片
      this.dialogVisible = true;
      // 解决选择相同文件不触发change事件问题
      this.$refs.file.value = "";
    },
    onDialogOpend() {
      const image = this.$refs["preview-img"];
      //   第一次预览过后如果图片发生变化，则需要更新裁切器 replace方法，或者销毁裁切器重新初始化
      if (this.cropper) {
        this.cropper.replace(this.previewImg);
        return;
      }
      this.cropper = new Cropper(image, {
        aspectRatio: 1,
        viewMode: 1,
        dragMode: "none",
        cropBoxResizable: false
        // 移动裁切器，会触发调用crop方法
        // crop(event) {
        //   console.log(event.detail.x);
        //   console.log(event.detail.y);
        //   console.log(event.detail.width);
        //   console.log(event.detail.height);
        //   console.log(event.detail.rotate);
        //   console.log(event.detail.scaleX);
        //   console.log(event.detail.scaleY);
        // }
      });
    },
    onDialogClosed() {
      // 对话框关闭，销毁裁切器
      // this.cropper.destroy()
    },
    onUpdateImg() {
      // 获取裁切图片对象
      this.cropper.getCroppedCanvas().toBlob(file => {
        // console.log(file)
        const fd = new FormData();
        fd.append("photo", file);
        // 请求提交图片
        updateUserPhoto(fd).then(res => {
          console.log(res);
          this.dialogVisible = false;
          // 直接把裁切结果文件对象转换成blob数据本地预览
          this.user.photo = window.URL.createObjectURL(file);
          //  this.user.photo = res.data.data.photo
          //   Bus.$emit('update-user',this.user)
        });
      });
    },
    onUpdateUser() {
      this.updateProfileLoading = true;
      updateUserProfile(this.user).then(res => {
        // console.log(res);
        this.$message({
          type: "success",
          message: "保存成功"
        });
        this.updateProfileLoading = false;
        // 发布用户信息修改消息
        Bus.$emit("update-user", this.user);
      });
    }
  }
};
</script>

<style scoped lang="less">
// .userForm {
//     margin-top: 3px;
// }
.preview-img-wrap {
  .preview-img {
    display: block;
    /* This rule is very important, please don't ignore this */
    max-width: 100%;
    height: 200px;
  }
}
</style>